package com.tihi.xml;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.graphics.RectF;

import com.tihi.util.LogUtil;
import com.tihi.util.StringUtils;

public class ViewNode extends BaseBean{
	/** 属性map */
	private HashMap<String, String> attrMap;
	private List<ViewNode> subNodes;
	
	public ViewNode() {
		attrMap = new HashMap<String, String>();
		subNodes = new ArrayList<ViewNode>();
	}
	
	public void addSubNode(ViewNode viewNode) {
		if(subNodes == null) {
			subNodes = new ArrayList<ViewNode>();
		}
		subNodes.add(viewNode);
	}
	
	public void addAttr(String key, String value) {
		if(attrMap == null) {
			attrMap = new HashMap<String, String>();
		}
		attrMap.put(key, value);
	}

	public HashMap<String, String> getAttrMap() {
		return attrMap;
	}

	public void setAttrMap(HashMap<String, String> attrMap) {
		this.attrMap = attrMap;
	}

	public List<ViewNode> getSubNodes() {
		return subNodes;
	}

	public void setSubNodes(List<ViewNode> subNodes) {
		this.subNodes = subNodes;
	}
	
	/**
	 * 节点描述: 控件名称 + bounds
	 * @return
	 */
	public String getNodeDesc() {
		StringBuffer nodeDesc = new StringBuffer();;
		if(attrMap != null) {
			for(String key : attrMap.keySet()) {
				if(NodeConst.CLASS.equals(key)) {
					String value = attrMap.get(key);
					nodeDesc.append(value.substring(value.lastIndexOf(".") + 1));
				}
				if(NodeConst.BOUNDS.equals(key)) {
					nodeDesc.append(attrMap.get(key));
				}
			}
		}
		return nodeDesc.toString();
	}
	
	/**
	 * 获取bounds矩形
	 * 原始数据格式： [0,0][720,1280]
	 * @return
	 */
	public RectF getBoundRectf() {
		RectF rectF = new RectF();
		if(attrMap != null) {
			String bounds = attrMap.get(NodeConst.BOUNDS);
			if(StringUtils.isNotEmpty(bounds)) {
				String tmp = bounds.replace("]", "");
				tmp = tmp.replace("[", ",");
				String []values = tmp.split(",");   //eg:  ,0,0,720,1280
				if(values != null && values.length == 5) {
					rectF.left = Float.valueOf(values[1]);
					rectF.top = Float.valueOf(values[2]);
					rectF.right = Float.valueOf(values[3]);
					rectF.bottom = Float.valueOf(values[4]);
				}
			}
		}
		return rectF;
	}
	
	public void print() {
		StringBuilder sb = new StringBuilder();
		if(attrMap != null) {
			for(Map.Entry<String, String> entry : attrMap.entrySet()) {
				sb.append("(" + entry.getKey() + ", " + entry.getValue() + ")");
			}
		}
		if(subNodes != null && subNodes.size() > 0) {
			sb.append("共：" + subNodes.size() + " 个子节点");
		}else {
			sb.append("共：0 个子节点");
		}
		LogUtil.log(sb.toString());
	}

}
